package view.components
{
	import flash.display.Bitmap;
	import flash.display.Sprite;
	
	import global.Resource;
	
	import model.load.DisplayObjectLoadMessage;
	
	import utils.DisplayTool;

	public class RemoteImage extends Sprite
	{
		protected var dWidth:int;
		protected var dHeight:int;
		private var dImg:Bitmap;
		private var loadMsg:DisplayObjectLoadMessage
		private var img:Bitmap;
		private var isAutoScale:Boolean;
		protected var isCache:Boolean;
		private var _loaded:Boolean;
		
		public function RemoteImage(imgWidth:int,imgHeight:int,defaultImgKey:String="face_head",isAutoScale:Boolean = true,isCache:Boolean = false)
		{
			this.isCache = isCache;
			this.isAutoScale = isAutoScale;
			this.mouseChildren = false;
			dWidth = imgWidth;
			dHeight = imgHeight;
			initDefaultImg(defaultImgKey);
			initLoadMsg();
		}
		
		public function get loaded():Boolean
		{
			return _loaded;
		}

		public function set loaded(value:Boolean):void
		{
			_loaded = value;
		}

		private function initLoadMsg():void
		{
			loadMsg = new DisplayObjectLoadMessage(loadComplete,null,isCache);
			loadMsg.isTimeOutReload = false;
		}
		
		protected function loadComplete(content:Bitmap):void
		{
			img = content;
			
			if (isAutoScale)
			{
				var scale:Number = Math.max(img.width / dWidth,img.height / dHeight);
				img.width = img.width / scale;
				img.height = img.height / scale;
				
			}
			else
			{
				img.x = (dWidth - img.width) * .5;
				img.y = (dHeight - img.height) * .5;
			}
			addChild(content);
			DisplayTool.removeChild(this,dImg);
		}
		
		private function initDefaultImg(defaultImgKey:String):void
		{
			if (defaultImgKey == null)
			{
				return;
			}
			
			dImg = Resource.getImg(defaultImgKey);
			dImg.width = dWidth;
			dImg.height = dHeight;
			addChild(dImg);
		}
		
		public function loadImg(url:String):void
		{
			loadMsg.url = url;
			loadMsg.send();
			_loaded = true;
		}
		
		public function clear():void
		{
			loadMsg.cancel();
			if (img)
			{
				img.bitmapData.dispose();
				
				DisplayTool.removeChild(this,img);
				img = null;
				if (dImg)
				{
					addChild(dImg);
				}
			}
		}
		
		public function destroy():void
		{
			clear();
			DisplayTool.removeAllChild(this);
			
			if (dImg)
			{
				dImg.bitmapData = null;
				dImg = null;
			}
			loadMsg = null;
			_loaded = false;
		}
	}
}